/**
 * This is not a production server yet!
 * This is only a minimal backend to get started.
 */

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { HttpExceptionFilter, TransformInterceptor, LoggerService, LoggerFactory } from '@nbase/nest-mods';
import { setupSwagger } from './config/swagger.config';

async function bootstrap() {
  // 创建应用实例，使用自定义 Logger 接管系统日志
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(),
    {
      logger: new LoggerService(),
      bufferLogs: true, // 缓冲日志，等待 logger 初始化完成
    }
  );

  // 全局前缀
  const globalPrefix = 'api';
  app.setGlobalPrefix(globalPrefix);

  // 启用 CORS
  app.enableCors({
    origin: process.env.CORS_ORIGIN || 'http://localhost:4200',
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization', 'Accept'],
  });

  // 全局验证管道
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      forbidNonWhitelisted: true,
    })
  );

  // 全局异常过滤器
  app.useGlobalFilters(new HttpExceptionFilter());

  // 全局响应拦截器
  app.useGlobalInterceptors(new TransformInterceptor());

  // Swagger API 文档配置
  setupSwagger(app, globalPrefix);

  const port = process.env.PORT || 3000;
  await app.listen(port, '0.0.0.0');

  // 使用 LoggerFactory 记录启动信息
  const logger = LoggerFactory.get('Bootstrap');
  logger.info(`🚀 Application is running on: http://localhost:${port}/${globalPrefix}`);
  logger.info(`📚 Swagger API Docs: http://localhost:${port}/api/docs`);
}

bootstrap();
